package game.lan;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import game.HallServer;
import game.entity.PlayingRole;
import game.lan.bean.LoginSessionBean;
import game.lan.bean.OpenLoginSessionBean;
import game.lan.cache.LoginSessionCache;
import game.module.announce.bean.AnnounceBean;
import game.module.announce.dao.AnnounceCache;
import game.module.announce.dao.AnnounceDao;
import game.module.dabt.logic.Calculator;
import game.module.dabt.logic.ChargeJindou;
import game.module.dabt.logic.ChargeRoomFee;
import game.module.kefu.bean.NewMailVo;
import game.module.kefu.bean.QuestionFeedback;
import game.module.kefu.logic.QuestionFeedbackManager;
import game.module.mail.logic.MailManager;
import game.module.message.processor.ScrollingMessageManager;
import game.session.SessionManager;
import io.netty.channel.Channel;
import lion.lan.ILanIoExecutor;
import lion.lan.Netty4LanServer;
import lion.netty4.message.RequestMessage;
import lion.netty4.message.SendToMessage;
import lua.LuaMessageHall.PushServerNotification; 
public class HallLanServerManager implements ILanIoExecutor {

	private static Logger logger = LoggerFactory.getLogger(HallLanServerManager.class);

	private Netty4LanServer lanServer;

	static class SingletonHolder {
		static HallLanServerManager instance = new HallLanServerManager();
	}

	public static HallLanServerManager getInstance() {
		return SingletonHolder.instance;
	}

	private HallLanServerManager() {
	}

	public void startServer(int port) {
		try {
			lanServer = new Netty4LanServer(port);
			lanServer.run(Runtime.getRuntime().availableProcessors(), this, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void shutdown() {
		if (lanServer != null) {
			lanServer.shutdown();
		}
	}

	@Override
	public void execute(final Channel channel, RequestMessage requestMessage) throws IOException {
		int msgCode = requestMessage.getMsgCode();
		logger.info("receive lan message ,msgCode={}", msgCode);
		// ip判断
		// Set<String> allowIpSet =
		// HallServer.getInstance().getServerConfig().getLanAllowIps();
		// if (channel.remoteAddress() != null) {
		// String ipStr = channel.remoteAddress().toString();
		// String aIp = StringUtils.split(ipStr, ":")[0].substring(1);
		// if (!allowIpSet.contains(aIp)) {
		// logger.warn("not valid ip lan request,ipAddr={}", ipStr);
		// return;
		// }
		// }
		switch (requestMessage.getMsgCode()) {
		case 10009:// 登录
			long sessionId = requestMessage.readLong();
			int uid = requestMessage.readInt();
			int serverId = requestMessage.readInt();
			LoginSessionCache.getInstance()
					.addLoginSession(new LoginSessionBean(sessionId, uid, System.currentTimeMillis(), serverId));
			break;
		case 11007:// open登录
			long openSessionId = requestMessage.readLong();
			String openId = requestMessage.readString();
			String accessToken = requestMessage.readString();
			LoginSessionCache.getInstance().addLoginSession(
					new OpenLoginSessionBean(openSessionId, openId, System.currentTimeMillis(), accessToken));
			break;
		case 10037:// 跑马灯公告
			final String subtitleContent = requestMessage.readString();
			final int repeateCount = requestMessage.readInt();
			logger.info("HallServer push 跑马灯公告!subtitleContent={},repeateCount={}", subtitleContent, repeateCount);
			HallServer.executorService.execute(new Runnable() {
				public void run() {
					PushServerNotification pushMsg = new PushServerNotification(subtitleContent, repeateCount);
					for (PlayingRole pr : SessionManager.getInstance().getAllPlayers()) {
						pr.getGamePlayer().writeAndFlush(pushMsg.build(pr.alloc()));
					}
				}
			});
			break;
		case 10039:// 大厅公告信息查询
			logger.info("query hall announce!");
			Collection<AnnounceBean> announceAll = AnnounceCache.getInstance().getAnnounceAll();
			SendToMessage announce2GmMessage = new SendToMessage(channel.alloc(), 10040);
			announce2GmMessage.writeInt(announceAll.size());
			for (AnnounceBean announceBean : announceAll) {
				announce2GmMessage.writeInt(announceBean.getId());
				announce2GmMessage.writeString(announceBean.getTitle());
				announce2GmMessage.writeString(announceBean.getContent());
			}
			channel.writeAndFlush(announce2GmMessage);
			break;
		case 10041:// 大厅某个公告查询
			int announceId = requestMessage.readInt();
			logger.info("query hall announce!id={}", announceId);
			announce2GmMessage = new SendToMessage(channel.alloc(), 10042);
			AnnounceBean announceBean = AnnounceCache.getInstance().getAnnounce(announceId);
			announce2GmMessage.writeInt(announceBean.getId());
			announce2GmMessage.writeString(announceBean.getTitle());
			announce2GmMessage.writeString(announceBean.getContent());
			channel.writeAndFlush(announce2GmMessage);
			break;
		case 10043:// 更新大厅的公告
			announceId = requestMessage.readInt();
			String announceTitle = requestMessage.readString();
			String announceContent = requestMessage.readString();
			announceBean = AnnounceCache.getInstance().getAnnounce(announceId);
			if (announceBean != null) {
				announceBean.setTitle(announceTitle);
				announceBean.setContent(announceContent);
				AnnounceDao.getInstance().updateAnnounce(announceTitle, announceContent, announceId);
			}
			else {
				announceBean = new AnnounceBean();
				announceBean.setTitle(announceTitle);
				announceBean.setContent(announceContent);
				AnnounceDao.getInstance().addAnnounce(announceBean);
				AnnounceCache.getInstance().addBean(announceBean);
			}
			announce2GmMessage = new SendToMessage(channel.alloc(), 10044);
			channel.writeAndFlush(announce2GmMessage);
			break;
		case 10101://客服反馈
			logger.info("---返回客服反馈列表---");
			SendToMessage questionFeedback2GmMessage = new SendToMessage(channel.alloc(), 10102);
			boolean isAnswer = requestMessage.readBool();
			List<QuestionFeedback> questionFeedbackList = QuestionFeedbackManager.getInstance().selectLimtQuestionFeedback(isAnswer);
			questionFeedback2GmMessage.writeString(JSON.toJSONString(questionFeedbackList));
			channel.writeAndFlush(questionFeedback2GmMessage);
			break;
		case 10103://客服反馈
			logger.info("---返回根据ID查询客服反馈---");
			SendToMessage singleQfb2GmMessage = new SendToMessage(channel.alloc(), 10104);
			int id = requestMessage.readInt();
			QuestionFeedback qfb = QuestionFeedbackManager.getInstance().selectQuestionFeedbackById(id);
			singleQfb2GmMessage.writeString(JSON.toJSONString(qfb));
			channel.writeAndFlush(singleQfb2GmMessage);
			break;
		case 10105://客服反馈
			logger.info("---更新客服反馈---");
			SendToMessage updateQfb2GmMessage = new SendToMessage(channel.alloc(), 10106);
			int id1 = requestMessage.readInt();
			String answer = requestMessage.readString();
			String mailVo = requestMessage.readString();
			//发送邮件
			NewMailVo newMailVo = JSONObject.parseObject(mailVo, NewMailVo.class);
			MailManager.getInstance().createMail(newMailVo.getToPlayerId(), newMailVo.getTemplateId(), newMailVo.getSendName(), newMailVo.getTitle(), newMailVo.getContent(), newMailVo.getListMailAttach(), newMailVo.getOtherMsg());
			//更新客服反馈
			QuestionFeedbackManager.getInstance().updateQuestionFeedback(id1, answer);
			updateQfb2GmMessage.writeString("success");
			channel.writeAndFlush(updateQfb2GmMessage);
			break;
		case 10107://跑马灯测试
			logger.info("---跑马灯测试---");
			SendToMessage pmdTest2GmMessage = new SendToMessage(channel.alloc(), 10108);
			int scrollid = requestMessage.readInt();
			String keyword = requestMessage.readString();
			logger.info("---跑马灯测试-模板信息--scrollid={}，keyword={}",scrollid,keyword);
			ScrollingMessageManager.getInstance().pushScrollingMessage(scrollid, keyword);
			
			pmdTest2GmMessage.writeString("success");
			channel.writeAndFlush(pmdTest2GmMessage);
			break;
		case 10109://定制邮件
			logger.info("---发送定制邮件---");
			SendToMessage sendCustomMailMessage = new SendToMessage(channel.alloc(), 10110);
			String customMailVo = requestMessage.readString();
			//发送邮件
			NewMailVo newcustomMailVo = JSONObject.parseObject(customMailVo, NewMailVo.class);
			if (newcustomMailVo.getToPlayerId()==-999)//群发所有
			{
				MailManager.getInstance().sendMailToAllPlayer(newcustomMailVo.getTemplateId(), newcustomMailVo.getSendName(), newcustomMailVo.getTitle(), newcustomMailVo.getContent(), newcustomMailVo.getListMailAttach(), newcustomMailVo.getOtherMsg());
			}else
			{
				MailManager.getInstance().createMail(newcustomMailVo.getToPlayerId(), newcustomMailVo.getTemplateId(), newcustomMailVo.getSendName(), newcustomMailVo.getTitle(), newcustomMailVo.getContent(), newcustomMailVo.getListMailAttach(), newcustomMailVo.getOtherMsg());
			}
			sendCustomMailMessage.writeString("success");
			channel.writeAndFlush(sendCustomMailMessage);
			break;
		case 21001://金豆结束
			logger.info("-----金豆结算-----");
			int jindou_di = requestMessage.readInt();
			int socreLen = requestMessage.readInt();
			int score[] = new int[socreLen];
			for(int i=0;i<socreLen;i++) 
				score[i] = requestMessage.readInt()*jindou_di;
			int playercount = requestMessage.readInt();
			
			List<Integer> players  = new ArrayList<Integer>();
			for(int i =0;i<playercount;i++) 
				players.add(requestMessage.readInt());
			String roomid = requestMessage.readString();
			short roundcount = requestMessage.readShort();
			int room_type = requestMessage.readInt();
			HallServer.executorService.execute(new Runnable() {
				@Override
				public void run() {
					Calculator.getInstance().calculateAllPlayerJindou(score, players,roomid,roundcount,room_type);
				}
			});
			break;
		case 21003://房卡收费
			
			short fee = requestMessage.readShort();
			byte type = requestMessage.readByte();
			int playcount = requestMessage.readInt();
			logger.info("fangka fufei type={},playcount={}",type,playcount);
			List<Integer> player = new ArrayList<Integer>();
			for(int i =0;i<playcount;i++) 
				player.add(requestMessage.readInt());
			HallServer.executorService.execute(new Runnable() {
				@Override
				public void run() {
					ChargeRoomFee.getInstance().tollfee(fee,type,player);
				}
			});
			break;
		case 21005://金豆房桌费的收取
			int jindou = requestMessage.readInt()/2;
			int count =requestMessage.readInt();
			List<Integer> gameplayers = new ArrayList<Integer>();
			for(int i =0;i<count;i++) {
				gameplayers.add(requestMessage.readInt());
			}
			ChargeJindou.getInstance().tollJindou(jindou, gameplayers);
			break;
		default:
			break;
		}
	}

}
